package book;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁的公平不公平实例
 * 公平锁，即先运行的线程先得到锁
 * 不公平锁，没有公平锁的规律
 * @author：涂有
 * @date 2017年2月28日 下午11:31:46
 */
public class ReentrantLockFairTest implements Runnable{

	private Lock lock;

	public ReentrantLockFairTest(boolean isFair){
		
		lock = new ReentrantLock(isFair);
	}
	
	public void run(){
		
		System.out.println("ThreadName=" + Thread.currentThread().getName() + "开始运行🚘");
		lock.lock();
		try{
			System.out.println("ThreadName=" + Thread.currentThread().getName() + "获取锁🔐");
		}finally{
			lock.unlock();
		}
	}
	
	public static void main(String[] args) {
		
		ReentrantLockFairTest lockTask = new ReentrantLockFairTest(true); //公平锁
//		ReentrantLockFairTest lockTask = new ReentrantLockFairTest(false); //不公平锁
		int count = 4;
		Thread[] ts = new Thread[count];
		for(int i = 0; i < count; i++){
			
			ts[i] = new Thread(lockTask);
		}
		for(int i = 0; i < count; i++){
			
			ts[i].start();
		}
	}
}
